//
//  PublishSuccessVC.m
//  TuYouAPP
//
//  Created by L on 14-2-21.
//
//

#import "PublishSuccessVC.h"
#import "PublishHeadView.h"
#import  "PublishVC.h"
#import <ShareSDK/ShareSDK.h>
#import "Util.h"
#import <AVOSCloud/AVOSCloud.h>
#import "UIImageView+WebCache.h"
@interface PublishSuccessVC ()
{
    UIScrollView *contentView;
    MWPhotoBrowser *browser;

}
@end

@implementation PublishSuccessVC

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        //self.view.backgroundColor = ColorRGB(230, 230, 230);
    }
    return self;
}

-(void)viewWillAppear:(BOOL)animated
{
   
    [super viewWillAppear:animated];
    if (!contentView) {
        [self loadDataAndView];
        
    }
}
-(void)loadDataAndView
{
    UIView *topView = [[UIView alloc]initWithFrame:CGRectMake(9, 10, 302, 67)];
    topView.backgroundColor = [UIColor whiteColor];
    topView.layer.borderWidth = 0.5;
    topView.layer.borderColor = [ColorRGB(212, 212, 212)CGColor];
    
    if (SystemIsiOS7()) {
        contentView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 64, 320, DEVICE_Height-64)];
    
    }
    else
    {
        contentView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 44, 320, DEVICE_Height-64)];
    }
    [self.view addSubview:contentView];
    contentView.backgroundColor = ColorRGB(230, 230, 230);
    
    UIView *headView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 302, 54)];
    UIImageView *headImage = [[UIImageView alloc]initWithFrame:CGRectMake(7, 7, 35, 35)];
  //  headImage.image = [UIImage imageNamed:@"headimage.jpeg"];
    
    [headImage setImageWithURL:[NSURL URLWithString:[TYUser currentUser].mHeadImgURL] placeholderImage:[UIImage imageNamed:@"70_70.png"]];
    [headView addSubview:headImage];
    UILabel *nameLabel = [[UILabel alloc]initWithFrame:CGRectMake(50, 5, 120, 21)];
    nameLabel.text = @"中国好声音";
    nameLabel.text =[TYUser currentUser].mUserDisplayName;
    [headView addSubview:nameLabel];
    
    
    CGSize constraintaa = CGSizeMake(85, CGFLOAT_MAX);
    CGSize sizeaa = [[TYUser currentUser].mUserDisplayName sizeWithFont:[UIFont systemFontOfSize:17] constrainedToSize:constraintaa lineBreakMode:NSLineBreakByWordWrapping];
    

    UIImageView *sexImage = [[UIImageView alloc]initWithFrame:CGRectMake(sizeaa.width +53, 10, 12, 12)];
    sexImage.image = [UIImage imageNamed:@"men.png"];
    
    [headView addSubview:sexImage];
    
    UIImageView *locImage = [[UIImageView alloc]initWithFrame:CGRectMake(50, 30, 10, 13)];
    locImage.image = [UIImage imageNamed:@"weizi.png"];
    [headView addSubview:locImage];
    
    UILabel *locLabel = [[UILabel alloc]initWithFrame:CGRectMake(65, 26, 205, 21)];
    locLabel.text = @"重庆三峡广场";
    locLabel.text = self.publish.mPointInfo;
    locLabel.font = [UIFont systemFontOfSize:12];
    locLabel.textColor = [UIColor grayColor];
    [headView addSubview:locLabel];
//    PublishHeadView *headView = [PublishHeadView shareView];
//    CGRect arect = headView.frame;
//    arect.origin.x = 0;
//    arect.origin.y = 0;
//    arect.size.height = 54;
//    arect.size.width = 320;
//    headView.frame =arect;
    [topView addSubview:headView];
   [contentView addSubview:topView];
    float orginY = 55;
    
    CGSize constraint = CGSizeMake(300, CGFLOAT_MAX);
    CGSize size = [self.publish.mContext sizeWithFont:[UIFont systemFontOfSize:16] constrainedToSize:constraint lineBreakMode:NSLineBreakByWordWrapping];

    UILabel *contentLabel = [[UILabel alloc]initWithFrame:CGRectMake(7, orginY, 290, size.height)];
    contentLabel.font = [UIFont systemFontOfSize:16];
    contentLabel.numberOfLines = 0;
    contentLabel.textColor = ColorRGB(104, 107, 119);
    contentLabel.backgroundColor = [UIColor clearColor];
    contentLabel.text =self.publish.mContext;
    [topView addSubview:contentLabel];
    
    orginY+=size.height+5;
    float btnX = 7;
    for (int i = 0; i<self.publish.mImgArr.count; i++) {
        if (btnX>260) {
            btnX = 7;
            orginY+=90;
        }
        UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake(btnX, orginY, 84, 84)];
        [btn addTarget:self action:@selector(photoTouched:) forControlEvents:UIControlEventTouchUpInside];
        UIImage *image = [self.publish.mImgArr objectAtIndex:i];
        [btn setImage:image forState:UIControlStateNormal];
        btn.tag = i+10;
        [topView addSubview:btn];
        btnX += 90;
    }
    
    if (self.publish.mImgArr.count == 0) {
        orginY-=90;
    }
  //  orginY+=90;
    
    UIImageView *typeimage = [[UIImageView alloc]initWithFrame:CGRectMake(7, orginY+90, 20, 20)];
    typeimage.image = [UIImage imageNamed:@"jingdian.png"];
    [topView addSubview:typeimage];
    UILabel *typeName = [[UILabel alloc]initWithFrame:CGRectMake(33, orginY+85, 250, 31)];
    typeName.text = self.publish.mRelInfo;
    typeName.font = [UIFont systemFontOfSize:12];
    typeName.textColor = [UIColor grayColor];
    [topView addSubview:typeName];
    
    orginY +=53;
    CGRect rect = topView.frame;
    rect.size.height +=orginY;
    topView.frame = rect;
    
    
    UIView *botView = [[UIView alloc]initWithFrame:CGRectMake(9, orginY+90, 302, 134)];
    botView.layer.borderWidth = 0.5;
    botView.layer.borderColor = [ColorRGB(212, 212, 212)CGColor];
    [contentView addSubview:botView];
    botView.backgroundColor = [UIColor whiteColor];
    UILabel *fenxianggei = [[UILabel alloc]initWithFrame:CGRectMake(11, 5, 50, 40)];
    fenxianggei.textColor = ColorRGB(104, 107, 119);
    fenxianggei.text = @"分享给";
    fenxianggei.font = [UIFont systemFontOfSize:16];
    [botView addSubview:fenxianggei];
    float botX = 16;
    for (int i = 0; i<4; i++) {
        UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake(botX, 50, 53, 53)];
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(botX-6, 100, 60, 30)];
        label.font= [UIFont systemFontOfSize:14];
        label.textAlignment = NSTextAlignmentCenter;
        label.textColor = ColorRGB(104, 107, 119);
        btn.tag = 100+i;
        if (i==0) {
            [btn setImage:[UIImage imageNamed:@"penyouquan.png"] forState:UIControlStateNormal];
            label.text = @"朋友圈";
        }
        else if (i == 1)
        {
            [btn setImage:[UIImage imageNamed:@"weibo.png"] forState:UIControlStateNormal];
            label.text = @"新浪微博";
            
        }
        else if (i == 2)
        {
            [btn setImage:[UIImage imageNamed:@"weixinhaoyou.png"] forState:UIControlStateNormal];
            label.text = @"微信好友";
            
            
        }
        else if (i == 3)
        {
            [btn setImage:[UIImage imageNamed:@"tenxun.png"] forState:UIControlStateNormal];
            label.text = @"腾讯微博";
        }
        [btn addTarget:self action:@selector(fenxiang:) forControlEvents:UIControlEventTouchUpInside];
        [botView addSubview:label];
        [botView addSubview:btn];
        botX += 72;
        
        
    }
    
    //   contentView.userInteractionEnabled = YES;
    contentView.contentSize = CGSizeMake(320, botView.frame.size.height+botView.frame.origin.y+10);
    
    

}


-(void)fenxiang:(UIButton *)btn
{
    int tag = btn.tag - 100;
    switch (tag) {
        case 0:
            [self pengyouquanBtn];
            break;
        case 1:
            [self weiboBtn];
            break;
        case 2:
            [self weixinhaoyouBtn];
            break;
        case 3:
            [self tengxunweiboBtn];
            break;
    
            
        default:
            break;
    }
}
-(void)pengyouquanBtn
{
    //NSString *imgurl = [Util makeSmallImgURL:[self.thePublish.mImgArr objectAtIndex:0]];
    
    
    NSMutableString *contentStr = [[NSMutableString alloc]initWithString:self.publish.mContext];
    if (contentStr.length>110) {
        [contentStr substringWithRange:NSMakeRange(0, 110)];
    }
    
    NSString *urlstr = [NSString stringWithFormat:@"http://app.tuyou.com/dongtai/%@",self.publish.objId];
    
    id<ISSContent> content = [ShareSDK content:contentStr
                                defaultContent:nil
                                         image:self.imageUrlArray.count!=0?[ShareSDK imageWithUrl:[self.imageUrlArray objectAtIndex:0]]:nil
                                         title:contentStr
                                           url:urlstr
                                   description:nil
                                     mediaType:SSPublishContentMediaTypeApp];
    
    id<ISSAuthOptions> authOptions = [ShareSDK authOptionsWithAutoAuth:YES
                                                         allowCallback:YES
                                                         authViewStyle:SSAuthViewStyleFullScreenPopup
                                                          viewDelegate:nil
                                               authManagerViewDelegate:nil];
    
    //在授权页面中添加关注官方微博
    
    
    [ShareSDK shareContent:content
                      type:ShareTypeWeixiTimeline
               authOptions:authOptions
             statusBarTips:YES
                    result:^(ShareType type, SSResponseState state, id<ISSPlatformShareInfo> statusInfo, id<ICMErrorInfo> error, BOOL end) {
                        
                        NSLog( @"%d",state);
                        if (state == SSPublishContentStateSuccess)
                        {
                            [SVProgressHUD showSuccessWithStatus:@"成功"];
                            NSLog(@"success");
                        }
                        else if (state == SSPublishContentStateCancel)
                        {
                            [SVProgressHUD showSuccessWithStatus:@"成功"];
                        }
                        else if (state == SSPublishContentStateFail)
                        {
                            if ([error errorCode] == -22003)
                            {
                                UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"TEXT_TIPS", @"提示")
                                                                                    message:[error errorDescription]
                                                                                   delegate:nil
                                                                          cancelButtonTitle:NSLocalizedString(@"TEXT_KNOW", @"知道了")
                                                                          otherButtonTitles:nil];
                                [alertView show];
                            }
                        }
                    }];
    
}
-(void)weiboBtn
{
    //id<ISSCAttachment> img;
    // id<ISSContent> content = [content addSinaWeiboUnitWithContent:@"发布微博" image:nil ];
    [GInfo shareClient].isAVOSCloud = NO;
    NSString *acon = [[NSString alloc]initWithString:self.publish.mContext];
    NSMutableString* contentStr =[[NSMutableString alloc]init];
    if (acon.length>110) {
        
        [contentStr appendString: [acon substringWithRange:NSMakeRange(0, 110) ]];
    }
    else
    {
        [contentStr appendString:acon];
    }
    [contentStr appendFormat:@"来自@%@ 的途友动态",self.publish.mTaguser.mUserDisplayName];
    NSString *urlstr = [NSString stringWithFormat:@"http://app.tuyou.com/dongtai/%@",self.publish.objId];
    [contentStr appendFormat:@":%@",urlstr];
 //   NSLog(@"%@",[Util makeBigImgURL:[self.imageUrlArray objectAtIndex:0]]);
    id<ISSContent> content = [ShareSDK content:contentStr
                                defaultContent:nil
                                         image:self.imageUrlArray.count!=0?[ShareSDK imageWithUrl:[Util makeBigImgURL:[self.imageUrlArray objectAtIndex:0]]]:nil
                                         title:nil
                                           url:nil
                                   description:nil
                                     mediaType:self.imageUrlArray.count!=0?SSPublishContentMediaTypeImage:SSPublishContentMediaTypeText];
    
    id<ISSAuthOptions> authOptions = [ShareSDK authOptionsWithAutoAuth:YES
                                                         allowCallback:YES
                                                         authViewStyle:SSAuthViewStyleFullScreenPopup
                                                          viewDelegate:nil
                                               authManagerViewDelegate:nil];
    
    //在授权页面中添加关注官方微博
    [authOptions setFollowAccounts:[NSDictionary dictionaryWithObjectsAndKeys:
                                    [ShareSDK userFieldWithType:SSUserFieldTypeName value:@"ShareSDK"],
                                    SHARE_TYPE_NUMBER(ShareTypeSinaWeibo),
                                    [ShareSDK userFieldWithType:SSUserFieldTypeName value:@"ShareSDK"],
                                    SHARE_TYPE_NUMBER(ShareTypeTencentWeibo),
                                    nil]];
    
    [ShareSDK shareContent:content
                      type:ShareTypeSinaWeibo
               authOptions:authOptions
             statusBarTips:YES
                    result:^(ShareType type, SSResponseState state, id<ISSPlatformShareInfo> statusInfo, id<ICMErrorInfo> error, BOOL end) {
                        
                        if (state == SSPublishContentStateSuccess)
                        {
                            [SVProgressHUD showSuccessWithStatus:@"分享成功"];
                            NSLog(@"success");
                        }
                        else if (state == SSPublishContentStateFail)
                        {
                            if ([error errorCode] == -22003)
                            {
                                UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"TEXT_TIPS", @"提示")
                                                                                    message:[error errorDescription]
                                                                                   delegate:nil
                                                                          cancelButtonTitle:NSLocalizedString(@"TEXT_KNOW", @"知道了")
                                                                          otherButtonTitles:nil];
                                [alertView show];
                            }
                        }
                    }];
    
    
}


-(void)weixinhaoyouBtn
{
    NSMutableString *contentStr = [[NSMutableString alloc]initWithString:self.publish.mContext];
    // [contentStr appendFormat:@"来自@%@的途友动态,",self.thePublish.mTaguser.mUserDisplayName];
    NSString *urlstr = [NSString stringWithFormat:@"http://app.tuyou.com/dongtai/%@",self.publish.objId];
    //  [contentStr appendFormat:@"下载应用:%@",urlstr];
    
    id<ISSContent> content = [ShareSDK content:contentStr
                                defaultContent:nil
                                         image:self.imageUrlArray.count!=0?[ShareSDK imageWithUrl:[self.imageUrlArray objectAtIndex:0]]:nil
                                         title:contentStr
                                           url:urlstr
                                   description:nil
                                     mediaType:SSPublishContentMediaTypeApp];
    
    id<ISSAuthOptions> authOptions = [ShareSDK authOptionsWithAutoAuth:YES
                                                         allowCallback:YES
                                                         authViewStyle:SSAuthViewStyleFullScreenPopup
                                                          viewDelegate:nil
                                               authManagerViewDelegate:nil];
    
    //在授权页面中添加关注官方微博
    [authOptions setFollowAccounts:[NSDictionary dictionaryWithObjectsAndKeys:
                                    [ShareSDK userFieldWithType:SSUserFieldTypeName value:@"ShareSDK"],
                                    SHARE_TYPE_NUMBER(ShareTypeSinaWeibo),
                                    [ShareSDK userFieldWithType:SSUserFieldTypeName value:@"ShareSDK"],
                                    SHARE_TYPE_NUMBER(ShareTypeTencentWeibo),
                                    nil]];
    
    [ShareSDK shareContent:content
                      type:ShareTypeWeixiSession
               authOptions:authOptions
             statusBarTips:YES
                    result:^(ShareType type, SSResponseState state, id<ISSPlatformShareInfo> statusInfo, id<ICMErrorInfo> error, BOOL end) {
                        
                        if (state == SSPublishContentStateSuccess)
                        {
                            [SVProgressHUD showSuccessWithStatus:@"分享成功"];
                            NSLog(@"success");
                        }
                        else if (state == SSPublishContentStateFail)
                        {
                            if ([error errorCode] == -22003)
                            {
                                UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"TEXT_TIPS", @"提示")
                                                                                    message:[error errorDescription]
                                                                                   delegate:nil
                                                                          cancelButtonTitle:NSLocalizedString(@"TEXT_KNOW", @"知道了")
                                                                          otherButtonTitles:nil];
                                [alertView show];
                            }
                        }
                    }];
}
-(void)tengxunweiboBtn
{
    
    NSMutableString *contentStr = [[NSMutableString alloc]initWithString:self.publish.mContext];
    [contentStr appendFormat:@"来自@%@ 的途友动态",self.publish.mTaguser.mUserDisplayName];
    NSString *urlstr = [NSString stringWithFormat:@"http://app.tuyou.com/dongtai/%@",self.publish.objId];
    [contentStr appendFormat:@":%@",urlstr];
    
    id<ISSContent> content = [ShareSDK content:contentStr
                                defaultContent:nil
                                         image:self.imageUrlArray.count!=0?[ShareSDK imageWithUrl:[self.imageUrlArray objectAtIndex:0]]:nil
                                         title:nil
                                           url:nil
                                   description:nil
                                     mediaType:self.imageUrlArray.count==0?SSPublishContentMediaTypeText:SSPublishContentMediaTypeImage];
    
    id<ISSAuthOptions> authOptions = [ShareSDK authOptionsWithAutoAuth:YES
                                                         allowCallback:YES
                                                         authViewStyle:SSAuthViewStyleFullScreenPopup
                                                          viewDelegate:nil
                                               authManagerViewDelegate:nil];
    
    //在授权页面中添加关注官方微博
    [authOptions setFollowAccounts:[NSDictionary dictionaryWithObjectsAndKeys:
                                    [ShareSDK userFieldWithType:SSUserFieldTypeName value:@"ShareSDK"],
                                    SHARE_TYPE_NUMBER(ShareTypeSinaWeibo),
                                    [ShareSDK userFieldWithType:SSUserFieldTypeName value:@"ShareSDK"],
                                    SHARE_TYPE_NUMBER(ShareTypeTencentWeibo),
                                    nil]];
    
    [ShareSDK shareContent:content
                      type:ShareTypeTencentWeibo
               authOptions:authOptions
             statusBarTips:YES
                    result:^(ShareType type, SSResponseState state, id<ISSPlatformShareInfo> statusInfo, id<ICMErrorInfo> error, BOOL end) {
                        
                        if (state == SSPublishContentStateSuccess)
                        {
                            [SVProgressHUD showSuccessWithStatus:@"分享成功"];
                            NSLog(@"success");
                        }
                        else if (state == SSPublishContentStateFail)
                        {
                            if ([error errorCode] == -22003)
                            {
                                UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"TEXT_TIPS", @"提示")
                                                                                    message:[error errorDescription]
                                                                                   delegate:nil
                                                                          cancelButtonTitle:NSLocalizedString(@"TEXT_KNOW", @"知道了")
                                                                          otherButtonTitles:nil];
                                [alertView show];
                            }
                        }
                    }];
    
}
-(void)photoTouched:(UIButton *)sender
{
    NSMutableArray *photos = [[NSMutableArray alloc] init];
    MWPhoto *photo;
    
    
    for (int i = 0; i< self.publish.mImgArr.count; i++) {
        photo = [MWPhoto photoWithImage:[self.publish.mImgArr objectAtIndex:i]];
        // photo.caption = @"Fireworks";
        [photos addObject:photo];
    }
    browser.hiddenTopBtn = NO;
    browser = [[MWPhotoBrowser alloc] initWithDelegate:self];
    browser.displayActionButton = NO;
    browser.zoomPhotosToFill = YES;
    
    [browser setCurrentPhotoIndex:sender.tag - 10];
    
    self.photos = photos;
    
    
    [self.navigationController pushViewController:browser animated:YES];
}


#pragma mark - MWPhotoBrowserDelegate
- (BOOL)photoBrowser:(MWPhotoBrowser *)photoBrowser isPhotoSelectedAtIndex:(NSUInteger)index
{
    NSLog(@"%D",index);
    return YES;
}

- (NSUInteger)numberOfPhotosInPhotoBrowser:(MWPhotoBrowser *)photoBrowser {
    return self.publish.mImgArr.count;
}
- (void)photoBrowser:(MWPhotoBrowser *)photoBrowser photoAtIndex:(NSUInteger)index selectedChanged:(BOOL)selected
{
    NSLog(@"%d",index);
}

- (id <MWPhoto>)photoBrowser:(MWPhotoBrowser *)photoBrowser photoAtIndex:(NSUInteger)index {
    if (index < _photos.count)
        return [_photos objectAtIndex:index];
    return nil;
}

- (void)viewDidLoad
{
    self.mPageName = @"发布成功";
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.Title = @"发布成功";
    self.LeftBarTitle = @"返回";
    self.RightBarTitle = @"继续发布";
}


-(void)leftBtnTouched:(id)sender
{
    NSArray *arr = self.navigationController.viewControllers;
    UIViewController *vc;
    if (self.ComeFrom == 1) {
        vc = [arr objectAtIndex:0];
    }
    else if (self.ComeFrom == 2)
    {
        vc = [arr objectAtIndex:1];
    }
    [self.navigationController popToViewController:vc animated:YES];
}
-(void)rightBtnTouched:(id)sender
{
    PublishVC *vc = [[PublishVC alloc]init];
    vc.comeFrom = self.ComeFrom;
    [self.navigationController pushViewController:vc animated:YES];
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
